import UnchangedExpression from "../impl/UnchangedExpression";
import Expression from "../interface/Expression";
import CoreExpression from "./CoreExpression";
import LimitExpression from "../LimitExpression";
import MetaData from "../MetaData";
import StringUtils from "../../utils/StringUtils";

class ExtendExpression extends CoreExpression {

    /*** 分页 */
    public paging(pageNum: number = 1, pageSize: number = 10): Expression {
        this.metadata.add(new UnchangedExpression(`LIMIT ${(pageNum - 1) * pageSize},${pageSize}`));
        return this;
    }

    /** 原生limit */
    public limit(limit: number) {
        return new LimitExpression(this.metadata, limit);
    }


    toLocaSql(): string {
        return "";
    }

    /** 子查询 */
    protected static subqueryFactory<T extends CoreExpression>(ex: T, metadata: MetaData, callback: (table: T) => any, alias: string = ""): T {
        let meta: MetaData = new MetaData(metadata);
        meta.isSubquery = true;
        meta.table = metadata.table;
        meta.isOn = metadata.isOn;
        meta.isWhere = metadata.isWhere;
        ex.setMetadata(meta);
        callback(ex)
        ex.setMetadata(metadata);
        // 判断是否有前缀
        if (meta.expressionList[0].type === 'prefix') {
            meta.add(new UnchangedExpression("(",meta), 1);
        } else {
            meta.add(new UnchangedExpression("(",meta),0);
        }
        meta.add(new UnchangedExpression(")"+ StringUtils.frontFill(alias, " "),meta));
        metadata.isOn = meta.isOn;
        metadata.isWhere = meta.isWhere;
        metadata.add(new UnchangedExpression( meta.toSql() , metadata))
        metadata.parameter.push(...meta.parameter)
        return ex;
    }
}

export = ExtendExpression;